package cn.tedu.v6;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

/**
 *Version 5 登陆与退出
 * Version 6 在线用户列表，统计上线名称
 *           消息转发  --交互--服务器客户端文字
 *
 */

public class Server {
    private ServerSocket serversocket;
    private static final Integer PORT=1019;
    private List<PrintWriter> allOut=new ArrayList<>();
    //1.存储在线客户，onlineUsers
    private List<String> onlineUsers=new ArrayList<>();
    private Map<String,String>userDatabase;

    public Server() {
        try {
            serversocket = new ServerSocket(PORT);
            userDatabase=new HashMap<>();
            userDatabase.put("海燕","123456");
            userDatabase.put("小宝","654321");

        } catch (BindException e) {
            System.out.println("请检查端口号，被占用~");
        } catch (IOException e) {
            System.out.println("客户端断开连接");
        }
    }
    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
               Socket socket = serversocket.accept();
               new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("连接失效");
        } finally {
            if (serversocket != null && serversocket.isClosed()) {
                try {
                    serversocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败~~");
                }
                System.out.println("服务器关闭成功~~Over");
            }
        }
    }
        public static void main (String[]args){
        new Server().start();
        }


    private synchronized void broadcastMessage(String message){
        for(PrintWriter pw:allOut){
            pw.println("消息广播："+message);
        }
    }
    //2.广播在线用户列表方法 updateOnlineUsers 更新在线人数
    //提醒;没有参数，传入字符串保存所有的客户端名称
    //2.1String userList="在线用户："+String.join("、",onlineUsers);
    //理解：拼接字符串，来客户名，记录一个客户端名
    //2.2来一个客户端，分发一个客户端消息：用户名消息
    private synchronized void updateOnlineUsers(){
        for(String userList:onlineUsers){
            userList="在线用户"+String.join(",",onlineUsers);
            System.out.println(userList);
            broadcastMessage(userList);
        }
    }


        private class ClientHandler implements Runnable {
            private Socket socket;
            private String ip;
            private PrintWriter pw;
            private BufferedReader br;
            private String username;
            private String password;

            public ClientHandler(Socket s) {

                this.socket = s;
               ip = socket.getInetAddress().getHostAddress();
                try {
                    br = new BufferedReader( new InputStreamReader(socket.getInputStream(),"UTF8"));
                    pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")));
                  synchronized (allOut){
                        allOut.add(pw);
                    }
                } catch (IOException e) {
                    System.out.println("客户端断开连接了");
                }
            }
            private boolean Login(String user,String pass){
                return userDatabase.containsKey(user)&&userDatabase.get(user).equals(pass);

            }
            private void handleChat(){
                new Thread(()->{
                    try{
                        String message;
                        while ((message= br.readLine())!=null){
                            System.out.println(ip+"客户端说："+message);
                            System.out.println("服务器请输入：");
                            broadcastMessage(message);
                        }
                    }catch(IOException e){
                        System.out.println("客户端发来的消息断开了");
                    }
                }).start();
                Scanner input=new Scanner(System.in);

                while (true){
                    System.out.println("服务器请输入");
                    String say=input.nextLine();
                    pw.println("服务器说："+say);
                    try{
                        say= br.readLine();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                    if(say.equalsIgnoreCase("exit")){
                        pw.println(ip+"推出聊天");
                        break;
                    }
                }
            }
            public void run() {
                try {
                    pw.println("请输入用户名：");
                   username= br.readLine();
                   pw.println("请输入密码：");
                   password=br.readLine();
                    if(Login(username,password)){
                        pw.println("登录成功，欢迎进入XX聊天室");
                        //3.判断客户端连接成功--加入集合中     3.1 【同步块：监视对象--集合】
                        //3.2 客户端登陆成功-名字加入集合中  方法？
                        onlineUsers.add(username);
                        synchronized (onlineUsers){
                            updateOnlineUsers();
                        }
                        handleChat();
                    }else{
                        pw.println("登陆失败，用户名或者密码错误");
                        socket.close();
                    }
                } catch (IOException e){
                    System.out.println("服务器端读写出问题！");
                } finally {
                    //4.同步块--从集合中依次移除用户名
                    synchronized (onlineUsers){
                        onlineUsers.remove(username);
                    }
                    synchronized (allOut){
                        allOut.remove(pw);
                    }

                    if(pw!=null)
                        pw.close();
                   if (br != null)
                      try {
                         br.close();
                      } catch (IOException e) {
                           System.out.println("读入流断开连接");
                        }
                    if(socket!=null&&!socket.isClosed()){
                        System.out.println(ip+"一个客户端退出客户端");
                        try {
                            socket.close();
                        } catch (IOException e) {
                            System.out.println(ip+"一个客户端推出链接");
                        }
                        System.out.println(ip+"一个客户端退出连接异常");
                    }
                }
            }
        }
    }




